package panel.sinaWeiCo
{
	import com.tencent.weibo.api.Authorize;
	import com.tencent.weibo.api.Content;
	import com.tencent.weibo.core.WeiboConfig;
	import com.tencent.weibo.operation.IRequestOperation;
	
	import flash.display.Sprite;
	import flash.display.Stage;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.KeyboardEvent;
	import flash.events.TimerEvent;
	import flash.geom.Rectangle;
	import flash.media.StageWebView;
	import flash.net.FileReference;
	import flash.text.TextField;
	import flash.ui.Keyboard;
	import flash.utils.ByteArray;
	import flash.utils.Timer;
	import flash.utils.getTimer;
	
	import main.LocalStoreInfo;
	
	/**
	 * 腾讯微博测试
	 * @author shaorui
	 */
	public class QQWeibo extends Sprite
	{
		/**你的APP ID*/
		private static var appKey:String = "801373997";
		/**你的APP秘钥*/
		private static var appSecret:String = "4cbf2f8a14926f36d1088a3d01b32e8b";
		/**腾讯微博配置对象*/
		private var weiboConfig:WeiboConfig;
		/**微博验证接口*/
		private var authorizeAPI:Authorize;
		/**内容发布接口*/
		private var contentAPI:Content;
		/**用于登录*/
		private var webView:StageWebView;
		/**@private*/
		private var message:String = "";
		private var _message:String;
		private var _bitmap:FileReference;
		private var _callBack:Function;
		private var _stage:Stage;
		private var _localCache:LocalStoreInfo = new LocalStoreInfo();
		private var _authorCallBack:Function;
		/**@private*/
		public function QQWeibo(value:Stage)
		{
			_stage = value;
			if(weiboConfig == null)
			{
				weiboConfig = WeiboConfig.getInstance();
				weiboConfig.initialize(appKey,appSecret,"http://www.tech-mx.com");
				//				weiboConfig.initialize(appKey,appSecret);
				weiboConfig.dataFormat = "json";
			}
		}
		
		public function sendWeibo(value:String,callBack:Function = null,bitmap:FileReference = null):void
		{
			_callBack = callBack;
			_message = value;
			_bitmap = bitmap;
			initUI();
		}
		
		/**@private*/
		protected function initUI():void
		{
			message = _message;
			executeMessage();
		}
		
		public function hasAuthored():Boolean
		{
			if(weiboConfig && weiboConfig.oauthToken != null && weiboConfig.oauthSecret != null || _localCache.readInfo("qqWeibo"))
			{
				return true;
			}else
			{
				return false;
			}
		}
		/**执行提示用户后，且用户确定的操作*/
		public function executeMessage(value:Function = null):void
		{
			_authorCallBack = value;
			_stage.addEventListener(KeyboardEvent.KEY_DOWN,onKeyDownHandler);
			//weiboConfig.clearCache();
			//判断是否已经授权,已经被授权，直接发微博
			if(weiboConfig.oauthToken != null && weiboConfig.oauthSecret != null || _localCache.readInfo("qqWeibo"))
			{
				if(_authorCallBack != null)
				{
					_authorCallBack();
				}else
				{
					sendNewWeibo();
				}
			}
			else
			{
				startAuth();
			}
		}
		
		protected function onKeyDownHandler(event:KeyboardEvent):void
		{
			if(event.keyCode == Keyboard.BACK)
			{
				event.preventDefault();
				event.stopPropagation();
				if(webView)
				{
					webView.stage = null;
				}
			}
		}
		
		/**发一条微博*/
		private function sendNewWeibo():void
		{
			var request:IRequestOperation;
			if(contentAPI == null)
				contentAPI = new Content();
			if(_bitmap)
			{
			request = contentAPI.addPic(message,_bitmap);
			}else
			{
			request = contentAPI.add(message);
			}
			request.addEventListener(Event.COMPLETE,addWeiboTokenHandler);
			request.addEventListener(IOErrorEvent.IO_ERROR,errorHandler);
		}
		/**
		 * 开始获取授权
		 */
		public function startAuth():void
		{
			var request:IRequestOperation;
			authorizeAPI = new Authorize();
			
			//获取未授权的Token
			request = authorizeAPI.requestToken();
			request.addEventListener(Event.COMPLETE,requestTokenHandler);
			request.addEventListener(IOErrorEvent.IO_ERROR,errorHandler);
		}
		/**
		 * 已获取未授权的Token,您需要进入腾讯的授权页面，按照提示进行操作
		 * @param event
		 */
		private function requestTokenHandler(event:Event):void
		{
			_localCache.storeInfo("qqWeibo",{oauthToken:weiboConfig.oauthToken,oauthSecret:weiboConfig.oauthSecret,applyTime:getTimer()});
			var viewWidth:int = _stage.stageWidth;
			var viewHeight:int = _stage.stageHeight;
			webView = new StageWebView();
			webView.stage = _stage;
			var x:int = 0;
			var y:int = 0;
			webView.viewPort = new Rectangle(x,y,viewWidth,viewHeight);
			var url:String = weiboConfig.encryptURLBase+"authorize?oauth_token="+weiboConfig.tempOauthToken+"&wap=3";
			webView.loadURL(url);
			var timer:Timer = new Timer(10,0);
			timer.addEventListener(TimerEvent.TIMER,useTimerCheckLocation);
			timer.start();
		}
		/**添加微博成功后，提示用户*/
		private function addWeiboTokenHandler(event:Event):void
		{
			_callBack();
			trace("微博已经发布成功!" + _message);
		}
		protected function useTimerCheckLocation(event:TimerEvent):void
		{
			var currentLocation:String = webView.location;
			var index:int = currentLocation.search(/oauth_verifier=[\d]{6}/g);
			var timer:Timer = event.target as Timer;
			if(index != -1)
			{
				timer.removeEventListener(TimerEvent.TIMER,function(...args):void{trace(webView.location)});
				timer.stop();
				var endChars:String = currentLocation.slice(index);
				endChars = endChars.replace("oauth_verifier=","");
				var request:IRequestOperation;
				request = authorizeAPI.accessToken(endChars);
				request.addEventListener(Event.COMPLETE,accessTokenHandler);
				request.addEventListener(IOErrorEvent.IO_ERROR,errorHandler);
				//remove webpage
				webView.stage = null;
				webView.dispose();
			}
			//如果用户取消
			index = currentLocation.search(/checkType=error/g);
			if(index != -1)
			{
				timer.removeEventListener(TimerEvent.TIMER,function(...args):void{trace(webView.location)});
				timer.stop();
				trace("因为您取消了授权，所以无法完成微博操作");
				//remove webpage
				webView.stage = null;
				webView.dispose();
			}
		}
		/**
		 * 已获取AccessToken,接着获取时间线数据
		 * @param event
		 */
		private function accessTokenHandler(event:Event):void
		{
			if(_authorCallBack != null)
			{
				_authorCallBack();
			}else
			{
			sendNewWeibo();
			}
		}
		/**
		 * 当请求失败，打印消息
		 */
		private function errorHandler(event:IOErrorEvent):void
		{
			trace("error:" + event.text);
		}
	}
}